package com.seven.ssa.service.impl;

import cn.dev33.satoken.stp.StpUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.seven.ssa.common.ErrorCode;
import com.seven.ssa.constant.RedisConstant;
import com.seven.ssa.exception.BusinessException;
import com.seven.ssa.mapper.UserMapper;
import com.seven.ssa.model.entity.User;
import com.seven.ssa.satoken.DeviceUtils;
import com.seven.ssa.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.redisson.api.RBitSet;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import java.time.LocalDate;
import java.util.ArrayList;
import java.util.BitSet;
import java.util.List;
import java.util.Objects;

import static com.seven.ssa.constant.UserConstant.ADMIN_ROLE;
import static com.seven.ssa.constant.UserConstant.USER_LOGIN_STATE;


/**
 * 用户服务实现类
 *
 * @author yupi
 */
@Service
@Slf4j
public class UserServiceImpl extends ServiceImpl<UserMapper, User>
        implements UserService {

    @Resource
    private UserMapper userMapper;

    /**
     * 盐值，混淆密码
     */
    private static final String SALT = "seven";
    @Autowired
    private RedissonClient redissonClient;

    @Override
    public long userRegister(String userAccount, String userPassword, String checkPassword) {
        // 1. 校验
        if (StringUtils.isAnyBlank(userAccount, userPassword, checkPassword)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "参数为空");
        }
        if (userAccount.length() < 4) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "用户账号过短");
        }
        if (userPassword.length() < 8 || checkPassword.length() < 8) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "用户密码过短");
        }
        // 密码和校验密码相同
        if (!userPassword.equals(checkPassword)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "两次输入的密码不一致");
        }
        synchronized (userAccount.intern()) {
            // 账户不能重复
            QueryWrapper<User> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("userAccount", userAccount);
            long count = userMapper.selectCount(queryWrapper);
            if (count > 0) {
                throw new BusinessException(ErrorCode.PARAMS_ERROR, "账号重复");
            }
            // 2. 加密
            String encryptPassword = DigestUtils.md5DigestAsHex((SALT + userPassword).getBytes());
            // 3. 插入数据
            User user = new User();
            user.setUserAccount(userAccount);
            user.setUserPassword(encryptPassword);
            boolean saveResult = this.save(user);
            if (!saveResult) {
                throw new BusinessException(ErrorCode.SYSTEM_ERROR, "注册失败，数据库错误");
            }
            return user.getId();
        }
    }

    @Override
    public User userLogin(String userAccount, String userPassword, HttpServletRequest request) {
        // 1. 校验
        if (StringUtils.isAnyBlank(userAccount, userPassword)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "参数为空");
        }
        if (userAccount.length() < 4) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "账号错误");
        }
        if (userPassword.length() < 8) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "密码错误");
        }
        // 2. 加密
        String encryptPassword = DigestUtils.md5DigestAsHex((SALT + userPassword).getBytes());
        // 查询用户是否存在
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("userAccount", userAccount);
        queryWrapper.eq("userPassword", encryptPassword);
        User user = userMapper.selectOne(queryWrapper);
        // 用户不存在
        if (user == null) {
            log.info("user login failed, userAccount cannot match userPassword");
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "用户不存在或密码错误");
        }
        // 3. 记录用户的登录态
        // request.getSession().setAttribute(USER_LOGIN_STATE, user);
        // P5：Sa-Token 登录，并指定设备，同端登录互斥
        StpUtil.login(user.getId(), DeviceUtils.getRequestDevice(request));
        StpUtil.getSession().set(USER_LOGIN_STATE, user);
        return user;
    }

    /**
     * 获取当前登录用户
     *
     * @param request
     * @return
     */
    @Override
    public User getLoginUser(HttpServletRequest request) {
        // 先判断是否已登录
        // Object userObj = request.getSession().getAttribute(USER_LOGIN_STATE);
        Object userObj = StpUtil.getLoginIdDefaultNull();//P5：改造获取用户登录态的逻辑
        if(Objects.isNull(userObj)){
            throw new BusinessException(ErrorCode.NOT_LOGIN_ERROR);
        }
        return (User) StpUtil.getSessionByLoginId(userObj).get(USER_LOGIN_STATE);
    }

    /**
     * 是否为管理员
     *
     * @param request
     * @return
     */
    @Override
    public boolean isAdmin(HttpServletRequest request) {
        // 仅管理员可查询
        // Object userObj = request.getSession().getAttribute(USER_LOGIN_STATE);
        Object userObj = StpUtil.getSession().get(USER_LOGIN_STATE);//P5：改造获取用户登录态的逻辑
        User user = (User) userObj;
        return user != null && ADMIN_ROLE.equals(user.getUserRole());
    }

    /**
     * 用户注销
     *
     * @param request
     */
    @Override
    public boolean userLogout(HttpServletRequest request) {
//        if (StpUtil.getSession().get(USER_LOGIN_STATE) == null) {//P5：改造获取用户信息的逻辑
//            throw new BusinessException(ErrorCode.OPERATION_ERROR, "未登录");
//        }
//        // P5：移除登录态改造
//        request.getSession().removeAttribute(USER_LOGIN_STATE);
        StpUtil.checkLogin();
        StpUtil.logout();
        return true;
    }

    /**
     * P1：添加用户签到记录
     * @param userId
     * @return
     */
    @Override
    public boolean addUserSignIn(long userId){
        // 获取Key，并通过key获取位图
        String key = RedisConstant.getUserSignInRedisKey(LocalDate.now().getYear(),userId);
        RBitSet signInBitSet = redissonClient.getBitSet(key);
        // 检查当天是否已经签到，如果当天还未签到，则设置为已签到
        if (!signInBitSet.get(LocalDate.now().getDayOfYear())) {
            return signInBitSet.set(LocalDate.now().getDayOfYear(), true);
        }
        return true;
    }

    /**
     * P1：获取用户签到记录
     * @param userId 用户id
     * @param year 年份
     * @return 签到记录
     */
    @Override
    public List<Integer> getUserSignInRecord(long userId, Integer year) {
        // 默认今年
        if (year == null) {year = LocalDate.now().getYear();}
        // 获取Key，并通过key获取位图，并加载位图到内存中，避免后续读取时发送多次请求
        String key = RedisConstant.getUserSignInRedisKey(year, userId);
        RBitSet signInBitSet = redissonClient.getBitSet(key);
        BitSet bitSet = signInBitSet.asBitSet();
        // 日期列表，用于显示签到记录
        List<Integer> dayList = new ArrayList<>();
        // 从 0 开始查找下一个被设置为 1 的位，避免过多循环消耗
        int i = bitSet.nextSetBit(0);
        while (i >= 0) {
            // 加入日期列表
            dayList.add(i);
            // 查找下一个被设置为 1 的位
            i = bitSet.nextSetBit(i + 1);
        }
        return dayList;
    }
}




